﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SmartSpace.Workflow
{
    public class WorkflowDbContext: DbContext
    {
        public WorkflowDbContext()
            : base("name=" + SmartSpace.Configuration.ConnectionStringName["workflow"])
        {
            if (SmartSpace.Configuration.IsAutomaticMigrations)
            {
                Database.SetInitializer<WorkflowDbContext>(new MigrateDatabaseToLatestVersion<WorkflowDbContext, DBMC>());
            }
            else
            {
                Database.SetInitializer<WorkflowDbContext>(null);
            }
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<WorkflowMetadata>().ToTable("wf_workflow");
            modelBuilder.Entity<WorkflowMetadata>().HasKey(p => p.Id);

            modelBuilder.Entity<ActivityMetadata>().ToTable("wf_activity");
            modelBuilder.Entity<ActivityMetadata>().HasKey(p => p.Id);

            modelBuilder.Entity<EventMetadata>().ToTable("wf_event");
            modelBuilder.Entity<EventMetadata>().HasKey(p => p.Id);

            modelBuilder.Entity<WorkflowInstance>().ToTable("wf_instance");
            modelBuilder.Entity<WorkflowInstance>().HasKey(p => p.Id);

            modelBuilder.Entity<WorkflowStep>().ToTable("wf_step");
            modelBuilder.Entity<WorkflowStep>().HasKey(p => p.Id);

            base.OnModelCreating(modelBuilder);
        }
    }

    internal sealed class DBMC : DbMigrationsConfiguration<WorkflowDbContext>
    {
        public DBMC()
        {
            AutomaticMigrationsEnabled = true;
            AutomaticMigrationDataLossAllowed = true;
        }
    }
}
